//
//  UserAccountViewModel.swift
//  sinaweibowj
//
//  Created by Macintosh on 15/12/17.
//  Copyright © 2015年 mactoinsh. All rights reserved.
//

import UIKit
import AFNetworking

//封装网络请求和业务逻辑
class UserAccountViewModel: NSObject {
    
    //定义用户模型对象的属性
    var  userAccount : UserAccount?
    
    override init() {
        
        userAccount = UserAccount.loadAccount()
        super.init()
    }
    
    //计算性属性  用户是否登录
    var userLogin:Bool {
        
        return userAccount?.access_token != nil
    }
    
    
    //用户头像的url
    var  headURL:NSURL?{
        
        let url = NSURL(string:userAccount?.avatar_large ?? "")
        return url
    }
    
    
    var token :String? {
    return userAccount?.access_token
    }
    
    //用户名
    var userName: String? {
        return  userAccount?.name
    }
    

    
    //加载用户token（请求标识）
    func loadAccessToken(code :String,finished:(isSuccess: Bool)-> ()){
        //接口名称
        let urlString = "oauth2/access_token"
        
        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
       
        NetWorkTools.sharedTools.requestJSONDict(.POST, urlString: urlString, parameters: parameters) { (dict, error) -> () in
          print(dict)
            if error != nil {
                //请求失败
                //执行失败的回调
                finished(isSuccess: false)
            return
            }
            
            //字典转模型
            let account = UserAccount(dict: dict!)
            //获取用户信息
            self.loadUserInfo(account, finished: finished)
            
        }
    }
    
    //获取用户信息
    private func loadUserInfo(account:UserAccount,finished:(isSuccess:Bool)->()){
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        if let  token = account.access_token,uid = account.uid {
            
            let parameters = ["access_token":token,"uid":uid]
            
      NetWorkTools.sharedTools.requestJSONDict(.GET, urlString: urlString, parameters: parameters, finished: { (dict, error) -> () in
        print(dict)
        if error != nil {
        //请求失败
            //执行失败的回调
            finished(isSuccess: false )
        return
        }
        //
        //获取用户信息
        let avatar_large = dict!["avatar_large"] as! String
        let name = dict!["name"] as!String
        //给account对象属性做赋值操作
        account.avatar_large = avatar_large
        account.name = name
        //存储用户信息的完整自定义对象
        account.saveAccount()
        //执行成功的回调
        finished(isSuccess: true)
      })
    }
  
    }
}
